<?php

/**
 * Created by PhpStorm.
 * User: CCA
 * Date: 2019/10/12
 * Time: 13:42
 */

namespace app\api\controller;


use app\api\BaseController;
use app\common\model\Adv;
use app\common\model\Appadv;
use app\common\model\Equipment as EquipmentModel;
use think\Session;
use JPush\Client as JPush;
use JPush\Exceptions\APIConnectionException;
use JPush\Exceptions\APIRequestException;

use UPush\template\IGtTransmissionTemplate;
use UPush\template\notify\IGtNotify;

/**
 * @title 首页
 */
class Home extends BaseController
{

    /**
     * @title 轮播图
     * @description
     * @param string ap_id 轮播图类型 1 false
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url //adv
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *information
     */
    public function adv()
    {
        $appadv_model = new Appadv();
        $type = input('param.type', '1'); #1:客户端 2：商城 3：服务端
        $condition = array();
        $condition['adv_address'] = $type;
        $condition['adv_type'] = 1;
        $adv_info = $appadv_model->app_get_adv_list($condition, 20, '', '');
        $config = db('config')->where('code', 'qiniu_http')->find();

        foreach ($adv_info as $k => &$item) {
            $url = $config['value'] . '/' . $item['adv_images'];
            $item['url'] = $url;
            switch ($item['ap_id']) {
                case '1':
                    #文章
                    $artice_info = db('article')->where(['article_id' => $item['artice_type']])->find();
                    $adv_info[$k]['adv_info'] = $artice_info['article_id'];
                    break;
                case '2':
                    #满减
                    $pmansong_info = db('pmansong')->where(['mansong_id' => $item['mansong_type']])->find();
                    $class_ids = '';

                    if (empty($pmansong_info['gc_three_id'])) {
                        $class_ids = $pmansong_info['gc_one_id'] . ',' . $pmansong_info['gc_two_id'];
                    } elseif (empty($pmansong_info['gc_two_id'])) {
                        $class_ids = $pmansong_info['gc_one_id'];
                    } else {
                        $class_ids = $pmansong_info['gc_one_id'] . ',' . $pmansong_info['gc_two_id'] . ',' . $pmansong_info['gc_three_id'];
                    }
                    $class_ids_array = explode(',', $class_ids);
                    $adv_info[$k]['adv_info'] = $class_ids_array;

                    break;
                case '3':
                    #折扣
                    $pxianshi_info = db('pxianshi')->where(['xianshi_id' => $item['xianshi_type']])->find();
                    $adv_info[$k]['adv_info'] = $pxianshi_info['xianshi_id'];
                    break;
                case '4':
                    #项目定制
                    $project_info = db('goodsproject')->where(['project_id' => $item['project_type']])->find();
                    $adv_info[$k]['adv_info'] = $project_info['project_id'];
                    break;
                default:
                    $adv_info[$k]['adv_info'] = $config['value'] . '/' . $item['video_type'];
                    break;
            }
        }

        return json_success_return($adv_info);
    }

    //关于我们22
    public function about()
    {
        $where['article_show'] = 1;
        $where['article_id'] = 22;
        $list = db('article')->where($where)->find();
        if ($list) {
            return json_success_return($list);
        } else {
            return json_fail_return($list);
        }
    }

    //联系我们23
    public function contact()
    {
        $where['article_show'] = 1;
        $where['article_id'] = 23;
        $list = db('article')->where($where)->find();
        if ($list) {
            return json_success_return($list);
        } else {
            return json_fail_return($list);
        }
    }

    /**
     * Notes:热门咨询  客户端服务端 通用
     * User: shen
     * Date: 2020/5/12
     * Time: 17:16
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function information()
    {
        $type = input('post.type', '0');  #0:客户端 1：服务端
        $where['ac_id'] = 1;
        $where['article_show'] = 1;
        $list = db('information')->where('ac_address', 'in', "{$type},2")->where($where)->order('article_sort desc')->select();
        $config = db('config')->where('code', 'qiniu_http')->find();

        foreach ($list as $key => $value) {
            $list[$key]['article_pic'] = $config['value'] . '/' . $value['article_pic'];
            $list[$key]['article_time'] = date('Y-m-d H:i:s', $value['article_time']);
            $article_content = htmlspecialchars_decode($value['article_content']);
            $new_content = strip_tags($article_content);
            $list[$key]['article_content'] = $new_content;
        }
        if ($list) {
            return json_success_return($list);
        } else {
            return json_fail_return($list);
        }
    }

    //    超级盟友
    public function link()
    {
        $list = db('link')->select();
        if ($list) {
            return json_success_return($list);
        } else {
            return json_fail_return($list);
        }
    }

    //    优惠券列表   面额，类别，项目。到期时间，满多少可用
    public function coupon()
    {
    }


    //核实验证码
    public function forgetpwd()
    {
        $phone = input('post.member_phone');
        $member_code = input('post.member_code');
        if (!preg_match("/^1[34578]\d{9}$/", $phone)) {
            return json_fail_return('手机号格式不正确');
        }
        if ($member_code != Session::get('code')) {
            return json_fail_return('验证码错误');
        } else {
            return json_success_return('验证码正确');
        }
    }

    //    密码重置
    public function reset()
    {
        $password_confirm = input('post.member_phone');
        $password_confirm = input('post.member_password_confirm');
        $password_new = input('post.member_password_new');
        if ($password_new != $password_confirm) {
            return json_fail_return('两次密码不一致');
        }
        $re = db('member')->where(['member_id' => $this->user_id])->update(['member_password' => md5($password_new)]);
        if ($re) {
            return json_success_return('修改成功');
        } else {
            return json_fail_return('修改失败');
        }
    }
    //    public function ceshi(){
    //        $session = new Session();
    //        $code2='1234';
    //        $session->set('user',$code2);
    //        $user2 = Session::get('user');
    //        echo $user2;
    //    }

    //    发送验证码
    public function send()
    {
        $phone = input('post.member_phone');
        if (!preg_match("/^1[34578]\d{9}$/", $phone)) {
            return json_fail_return('手机号格式不正确');
        }
        //接口账号
        $apiKey = '2286290010';
        //接口密码
        $apiSecret = '887e45f4adbc87399e88';
        $code = mt_rand(999, 9999); //生成四位随机数
        $status = 1;
        $record = $this->sendlist($code, $status);
        if (!$record) {
            return json_fail_return('插入记录失败');
        }
        $session = new Session();
        $session->set('code', $code);
        //短信内容(【签名】+短信内容)，系统提供的测试签名和内容，如需要发送自己的短信内容请在启瑞云平台申请签名和模板
        $content = '【山陆久】你好，你的验证码是' . $code . '，请在3分钟内验证完毕。';
        vendor('code.SendDemo');
        $sms = new \SendDemo($apiKey, $apiSecret);
        $result = $sms->send($phone, $content);
        $list_code = json_decode($result, true);
        if ($list_code["success"] == 'true') {
            return json_success_return('发送成功');
        } else {
            return json_fail_return('发送失败');
        }
    }

    //  发送验证码记录
    public function sendlist($code, $status)
    {
        $data['code'] = $code;
        $data['status'] = $status;
        $data['time'] = date('Y-m-d H:i:s');
        $list = db('sendrecord')->insert($data);
        return $list;
    }

    //    推送
    public function push()
    {
        $text = input('post.text');
        vendor('push.autoload');
        $app_key = '044a576845c53de28cbb703d';
        $master_secret = '343467a72d42499bd7116aaa';
        $client = new \JPush($app_key, $master_secret);
        $client->push()->setPlatform('all')->addAllAudience()->setNotificationAlert("$text")->send();
    }

    #上传图片
    public function image_upload()
    {
        $old_name = $_FILES['file']['name'];
        $file_type = array('0' => 'gif', '1' => 'jpg', '2' => 'jpeg', '3' => 'png', '4' => 'JPG', '5' => 'JPEG', '6' => 'PNG');
        $file_foot_name = substr($_FILES['file']['name'], (strripos($_FILES['file']['name'], ".")) + 1);
        if (!in_array($file_foot_name, $file_type)) {
            $upload_info['msg'] = 1;
            return json_fail_return($upload_info);
        }
        $upload_info = upload_qiniu('file');
        return json_success_return($upload_info);
    }

    #上传图片
    public function im_image_upload()
    {
        $old_name = $_FILES['file']['name'];
        // $file_type = array('0' => 'gif', '1' => 'jpg', '2' => 'jpeg', '3' => 'png', '4' => 'JPG', '5' => 'JPEG', '6' => 'PNG');
        // $file_foot_name = substr($_FILES['file']['name'], (strripos($_FILES['file']['name'], ".")) + 1);
        // if (!in_array($file_foot_name, $file_type)) {
        //     $upload_info['msg'] = 1;
        //     return json_fail_return($upload_info);
        // }
        $upload_info = upload_qiniu('file');

        $data['src'] = 'http://33wang.douyinhot.com' . '/' . $upload_info['data'];
        $new = [
            'code' => 0,
            'msg' => '上传成功',
            'data' => [
                'src' => $data['src']
            ],
        ];
        return im_return($new);
    }


    // 联系客服
    public function contact_customer_servic()
    {
        $data = input('post.');

        if (empty($data['type'])) {
            return json_fail_return('参数错误');
        }

        if ($data['type'] == 1) {
            #客户端
            $result = db('document')->where(['document_code' => 'kehuCustomer'])->find();
            $content = htmlspecialchars_decode($result['document_content']);
            $new_content = strip_tags($content);
            $result['document_content'] = $new_content;
        } else {
            #服务端
            $result = db('document')->where(['document_code' => 'fuwuCustomer'])->find();
            $content = htmlspecialchars_decode($result['document_content']);
            $new_content = strip_tags($content);
            $result['document_content'] = $new_content;
        }
        json_success_return($result);
    }

    // 版本号
    public function upgrade_version()
    {
        $result = db('version')->where(['version_type' => 1])->find();
        json_success_return($result);
    }

    public function Jpush()
    {
        $data = input('post.');
        require_once APP_PATH . '/../extend/JPush/autoload.php';

        // 构建鉴权对象
        $auth = new Jpush('f8fda95da1d7f5894955ec63', 'cd9b733d9179de75279edf16');

        $result = $auth->push()
            ->setPlatform('all') #推送平台
            ->addAllAudience()
            ->setNotificationAlert($data['message'])  //你要推送的信息              
            ->send();
        return json_encode($result);  //返回发送结果

    }

    #单推
    public function alonePush()
    {
        json_success_return(pushMessageToSingle('通知', 'fd2708efdd59ee4a1ee3c49c8841a4ec', '22')); //返回发送结果
    }

    #群推
    public function Upush()
    {
        json_success_return(pushMessageToApp()); //返回发送结果
    }

    #绑定别名
    public function bindAlias()
    {
        $data = input('post.');
        json_success_return(bindAlias('BxYQ7rO8AB7mcyjeTVHMcA', 'zjw', '93ebd7c24cb42061c87aa48b97d3609e')); //返回发送结果
    }

    #推送结果
    public function getPushResult()
    {
        $data = input('post.');
        json_success_return(getPushResult($data)); //返回发送结果
    }

    #极光注册
    public function JmRegist()
    {
        $data = input('post.');
        //批量注册客服
        $kefu_info = db('work_zhu')->select();

        foreach ($kefu_info as $k => $v) {
            $data = [
                'username' => 'admin-' . $v['account'],
                'password' => 123456,
                'nickname' => 'admin-' . $v['account'],
                'avatar' => 'http://33wang.douyinhot.com/4bad2202003051614055110.jpg',
                'signature' => '专注为汽车行业服务'
            ];
            JmRegist($data);
        }
        json_success_return(); //返回发送结果
    }

    #获取消息
    public function getJmText()
    {
        $data = input('post.');
        json_success_return(getJmText($data['username'], $data['begin_time'], $data['end_time'])); //返回发送结果
    }


    /**
     * Notes: 获取后台配置值
     * User: shen
     * Date: 2020/4/24
     * Time: 14:51
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function get_config()
    {
        $code = input('param.code');
        if (empty($code)) {
            return json_fail_return('参数错误');
        }

        $config_info = db('config')->where(['code' => $code])->find();
        json_success_return($config_info, '操作成功');
    }

    /**
     * Notes:文章详情
     * User: shen
     * Date: 2020/4/24
     * Time: 15:46
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function get_article_info()
    {
        $article_id = intval(input('article_id'));
        $where = [
            'a.article_id' => $article_id,
        ];
        $info = db('article')->alias('a')
            ->join('articleclass b', 'a.ac_id = b.ac_id')->where($where)->field('a.*,b.ac_name')->find();
        if ($info) {
            $info['article_time'] = date('Y-m-d H:i:s', $info['article_time']);
            $article_content = htmlspecialchars_decode($info['article_content']);
          //  $new_content = strip_tags($article_content);
            $info['article_content'] = $article_content;
        } else {
            $info = array();
        }
        json_success_return($info);
    }

    /**
     * Notes:客户端首页广告位
     * User: shen
     * Date: 2020/4/24
     * Time: 15:46
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function get_index_adv()
    {
        $type = input('type', '1');

        $info = db('adv')->where(['adv_address' => $type, 'adv_enabled' => 1, 'adv_type' => 2])->where('adv_startdate', '<', time())->where('adv_enddate', '>', time())->order('adv_sort', 'asc')->select();
        if ($info) {
            $config = db('config')->where('code', 'qiniu_http')->find();
            foreach ($info as $key => $value) {
                $info[$key]['pic'] = $config['value'] . '/' . $value['adv_images'];

                switch ($value['ap_id']) {
                    case '1':
                        #文章
                        $artice_info = db('article')->where(['article_id' => $value['artice_type']])->find();
                        $info[$key]['adv_info'] = $artice_info['article_id'];
                        break;
                    case '2':
                        #满减
                        $pmansong_info = db('pmansong')->where(['mansong_id' => $value['mansong_type']])->find();
                        $class_ids = '';

                        if (empty($pmansong_info['gc_three_id'])) {
                            $class_ids = $pmansong_info['gc_one_id'] . ',' . $pmansong_info['gc_two_id'];
                        } elseif (empty($pmansong_info['gc_two_id'])) {
                            $class_ids = $pmansong_info['gc_one_id'];
                        } else {
                            $class_ids = $pmansong_info['gc_one_id'] . ',' . $pmansong_info['gc_two_id'] . ',' . $pmansong_info['gc_three_id'];
                        }
                        $class_ids_array = explode(',', $class_ids);
                        $info[$key]['adv_info'] = $class_ids_array;

                        break;
                    case '3':
                        #折扣
                        $pxianshi_info = db('pxianshi')->where(['xianshi_id' => $value['xianshi_type']])->find();
                        $info[$key]['adv_info'] = $pxianshi_info['xianshi_id'];
                        break;
                    case '4':
                        #项目定制
                        $project_info = db('goodsproject')->where(['project_id' => $value['project_type']])->find();
                        $info[$key]['adv_info'] = $project_info['project_id'];
                        break;
                    default:
                        $info[$key]['adv_info'] = $config['value'] . '/' . $value['video_type'];
                        break;
                }
            }
        } else {
            $info = array();
        }
        json_success_return($info);
    }

    /**
     * @title  异步接口支付返回结果
     * @description
     * @param string payment_code 支付方式alipay
     * @param string
     * @return {"code":200,"msg":"succeess"}
     * @author zjw
     * @url /Order/get_asynchronous_res
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_asynchronous_res()
    {
        #如果支付失败了，订单状态改为取消
        if ($_POST['code'] == "SUCCESS") {
            db('app_order')->where(['order_sn'=>$_POST['merchantOrderNo']])->update(['order_status'=>1]);

            $app_order_info = db('app_order')->where(['order_sn'=>$_POST['merchantOrderNo']])->find();
            $order_ids = explode(',',$app_order_info['order_ids']);
            foreach($order_ids as $k => $v){
                db('order')->where(['order_id'=>$v])->update(['order_state'=>20,'payment_time'=>time()]);
            }
            return 'ok';
        } else {
            return 'error';
        }
    }

    /**
     * @title  项目定制 异步接口支付返回结果
     * @description
     * @param string payment_code 支付方式alipay
     * @param string
     * @return {"code":200,"msg":"succeess"}
     * @author zjw
     * @url /Order/get_asynchronous_res
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_project_asynchronous_res()
    {
        #如果支付失败了，订单状态改为取消
        if ($_POST['code'] == "SUCCESS") {
            $order_info = db('orderproject')->where(['order_sn' => $_POST['merchantOrderNo']])->find();

            #改支付状态
            db('orderpay')->where(['pay_sn' => $order_info['pay_sn']])->update(['api_paystate' => 1]);

            #改订单状态
            db('orderproject')->where(['pay_sn' => $order_info['pay_sn']])->update(['order_state' => 20, 'payment_time' => time()]);

            #改支付状态
            $order_info = db('order')->where(['pay_sn' => $order_info['pay_sn']])->find();
            db('order')->where(['pay_sn' => $order_info['pay_sn']])->update(['payment_time' => time()]);
            db('app_order')->where(['order_ids' => $order_info['order_id']])->update(['order_status' => 1]);


            #更新订单缓存表，用于统计数据
            $order_info = db('orderproject')->where(['pay_sn' => $order_info['pay_sn']])->find();
            db('statorder')->where(['order_id' => $order_info['order_id']])->update(['order_state' => 20]);

            return 'ok';
        } else {
            return 'error';
        }
    }



     /**
     * @title  自动收货接口
     * @description
     * @return {"code":200,"msg":"succeess"}
     * @author lihe
     * @url /Home/auto_receipt_order
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function auto_receipt_order(){
        $order = model('order');
        $msg = $order->autoReceiptOrder();

        json_success_return(['data' => $msg]);   
    }


    /**
     * Notes:服务单用户三天内不点击自动服务完成
     * User: shen
     * Date: 2020/5/23
     * Time: 11:20
     */
    public function s_order_automatic_finish()
    {
        $equipmentModel = new EquipmentModel();
        $result = $equipmentModel->s_order_automatic_finish();
        return json_success_return($result);
    }

}
